<template>
  <el-dialog
    title="分配角色"
    :visible.sync="roleVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @click="handleCancel"
  >
    <el-checkbox-group v-model="checkRoles">
      <el-checkbox v-for="role in roles" :key="role.id" :label="role.id">{{
        role.roleName
      }}</el-checkbox>
    </el-checkbox-group>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleAssignRole">确 定</el-button>
    </div>
  </el-dialog>
</template>
  
  <script>
import { assignRoleApi } from "@/Api/UserApi";
import { rolesApi, roleByUserIdApi } from "@/Api/RoleApi";
export default {
  props: ["roleVisible"],
  data() {
    return {
      roles: [],
      formLabelWidth: "120px",
      userId: "",
      checkRoles: [], //选中角色
    };
  },
  mounted() {
    this.loadRoles();
  },
  methods: {
    handleCancel() {
      this.$emit("closeAddDialog");
    },
    //
    async handleAssignRole() {
      try {
        const data = {
          userId: this.userId,
          roleIds: this.checkRoles,
        };
        const res = await assignRoleApi(data);

        if (res.status == 200) {
          this.$emit("closeAddDialog", true);
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 1000,
          });
        }
      } catch (error) {
        console.log(error);
        this.$message({
          message: "系统异常",
          type: "error",
          duration: 1000,
        });
      }
    },
    //
    async openDialog(userId) {
      this.userId = userId;
      try {
        const res = await roleByUserIdApi(userId);

        if (res.status == 200) {
          this.checkRoles = res.data.map((item) => item.id);
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 1000,
          });
        }
      } catch (error) {
        console.log(error);
        this.$message({
          message: "系统异常",
          type: "error",
          duration: 1000,
        });
      }
    },

    //加载所有角色
    async loadRoles(userId) {
      try {
        const res = await rolesApi();
        this.roles = res.data;

        if (res.status == 200) {
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 1000,
          });
        }
      } catch (error) {
        console.log(error);

        this.$message({
          message: "系统异常",
          type: "error",
          duration: 1000,
        });
      }
    },
  },
};
</script>
  
  <style lang="less" scoped>
</style>    